#include <boost/asio.hpp>
#include <iostream>

//////////////////////////////
///TCP异步服务器
//////////////////////////////

void on_accept(const boost::system::error_code& ec, boost::asio::ip::tcp::socket socket) {
    if (!ec) {
        std::cout << "Client connected: " << socket.remote_endpoint() << std::endl;

        // 异步读取数据
        auto buffer = std::make_shared<std::vector<char>>(128);
        socket.async_read_some(boost::asio::buffer(*buffer), 
            [buffer](const boost::system::error_code& ec, std::size_t length) {
                if (!ec) {
                    std::cout << "Received: " << std::string(buffer->data(), length) << std::endl;
                }
            });
    } else {
        std::cerr << "Accept failed: " << ec.message() << std::endl;
    }
}

int main() {
    boost::asio::io_context io_context;

    // 创建监听器
    boost::asio::ip::tcp::acceptor acceptor(
        io_context, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 8080));

    // 异步接受连接
    acceptor.async_accept(
        [&acceptor](const boost::system::error_code& ec, boost::asio::ip::tcp::socket socket) {
            on_accept(ec, std::move(socket));
        });

    std::cout << "Server is running on port 8080..." << std::endl;

    // 启动事件循环
    io_context.run();

    return 0;
}


//////////////////////////////
///TCP同步服务器
//////////////////////////////

// int main() {
//     try {
//         boost::asio::io_context io_context;

//         // 创建监听器
//         boost::asio::ip::tcp::acceptor acceptor(
//             io_context, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 8080));

//         std::cout << "Server is running on port 8080..." << std::endl;

//         // 接受客户端连接
//         boost::asio::ip::tcp::socket socket(io_context);
//         acceptor.accept(socket);

//         std::cout << "Client connected: " << socket.remote_endpoint() << std::endl;

//         // 接收客户端数据
//         char buffer[128];
//         size_t len = socket.read_some(boost::asio::buffer(buffer));
//         std::cout << "Received: " << std::string(buffer, len) << std::endl;

//         // 发送响应
//         std::string response = "Hello, Client!";
//         boost::asio::write(socket, boost::asio::buffer(response));

//         // 关闭连接
//         socket.close();
//     } catch (const std::exception& e) {
//         std::cerr << "Error: " << e.what() << std::endl;
//     }

//     return 0;
// }
